<?php
// +----------------------------------------------------------------------
// | Park 停车场
// +----------------------------------------------------------------------
// | Author: cart <xiaozhao755@gmail.com>
// +----------------------------------------------------------------------
// | Datetime: 2018-3-8 14:01:00
// +----------------------------------------------------------------------
// | Copyright: 微量科技
// +----------------------------------------------------------------------

namespace app\ice\controller;

use think\Validate;
use think\Log;
use think\Db;
use org\BaiduMap;
use think\Model;
use think\Loader;
use org\HMongodb;
use think\Exception;
use app\dv1\model\Shop;

class Pay extends Init
{
    private $OrderModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->OrderModel = Loader::model('Order');
    }

    // 支付
    public function goPay()
    {
        try {
            $post = input('post.');
            \think\Loader::import('wxpay.Autoloader');
            $user = Loader::model('User')->where(['id' => $post['uid']])->find();
            $openid = $user->openid;
            $orderInfo = Loader::model('Order')->where(['order_id' => $post['nextAction']['id']])->find();
            if($post['money'] != $orderInfo['goods_price']){
                return ['data' => [], 'code' => 400, 'msg' => '订单异常', 'status' => false];
            }

            if($orderInfo['pay_status'] == 1){
                return ['data' => [], 'code' => 400, 'msg' => '已经支付过了，等待处理中', 'status' => false];
            }

            // db::name('order_kd')->where('id',$post['id'])->update(['couponid'=>$post['couponid'],'updated_at'=>time()]);
            $orderid = \WxPayConfig::$mchid.$orderInfo['order_id'].rand(0000,9999);
            $attach = json_encode(array(
                'type' => 2,
                'uid' => $post['uid'],
                'id' => $post['nextAction']['id'],
            ));
            $input = new \WxPayUnifiedOrder();
            //         文档提及的参数规范：商家名称-销售商品类目
            $input->SetBody('冰川泥');
            $input->SetAttach($attach);
            $input->SetOut_trade_no($orderid);
            $input->SetTotal_fee($post['money']*100);
            $input->SetNotify_url(config('wxcallback')."/ice/pay/notify");//需要自己写的notify.php
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openid);
            $order = \WxPayApi::unifiedOrder($input);
            header("Content-Type: application/json");
            $res = $this->getJsApiParameters($order);
            return ['data' => $res, 'code' => 200, 'msg' => '支付成功', 'status' => true];
        } catch (Exception $e) {
            return ['data' => [], 'code' => 400, 'msg' => $e->getMessage(), 'status' => false];
        }
    }

        // 支付
    public function savePayStatus()
    {
        try {
            $post = input('post.');
            \think\Loader::import('wxpay.Autoloader');
            $user = Loader::model('User')->where(['id' => $post['uid']])->find();
            $openid = $user->openid;
            $res = Loader::model('Order')->where(['order_id' => $post['nextAction']['id']])->update(['pay_status'=>1]);
            return ['data' => $res, 'code' => 200, 'msg' => '支付成功', 'status' => true];
        } catch (Exception $e) {
            return ['data' => [], 'code' => 400, 'msg' => $e->getMessage(), 'status' => false];
        }
    }

    private function getJsApiParameters($UnifiedOrderResult)
    {
        //判断是否统一下单返回了prepay_id
        if (!array_key_exists("appid", $UnifiedOrderResult)
            || !array_key_exists("prepay_id", $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == "") {
            throw new \WxPayException("参数错误");
        }
        $jsapi = new \WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult["appid"]);
        $timeStamp = time();
        $jsapi->SetTimeStamp("$timeStamp");
        $jsapi->SetNonceStr(\WxPayApi::getNonceStr());
        $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
        $jsapi->SetSignType("MD5");
        $jsapi->SetPaySign($jsapi->MakeSign());
        $parameters = json_encode($jsapi->GetValues());
        return $parameters;
    }

        /**
     * [微信支付回调]
     */
    public function notify(){
        //接收异步回调的返回值
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        //xml转array
        $datas = json_decode(json_encode(simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA)),TRUE);
        $data = json_encode($datas);
        Db::name('Log')->insert(['log'=>$data]);
        //回调数据中获得的订单id（唯一）
        $out_trade_no = $datas['out_trade_no'];
        $time = $datas['time_end'];
        $attach = json_decode($datas['attach'], true);
        //查询有无订单记录
        $order_data = Loader::model('Order')->where(['order_id' => $attach['id']])->find();
        $res = false;
        if ($order_data) {
          //修改订单支付状态
            $res = Loader::model('Order')->where(['order_id' => $attach['id']])->update(['status'=>1]);
        }
        //返回码1是成功
        if($res){
            //订单状态满足要求，停止插入数据
            $notify = Loader::model('Order')->where(['order_id' => $attach['id']])->find();
            //2：已支付成功
            if ($notify['status']==1){
            //回调数据保存
                $data['d_openid'] = $datas['openid'];
                $data['d_total_fee'] = $datas['total_fee'];
                //用于累计的金额
                $total_fee = $datas['total_fee'];
                //获取支付订单信息
                $notify_out_trade_no = Db::name('Notify')->getNotifyInfo($attach['id']);
                if (null == $notify_out_trade_no ) {
                    Db::name('Notify')->addNotifyInfo($datas,$attach['id']);
                }
                // $api_order_data = Loader::model('Order')->where(['order_id' => $attach['id']])->find();


                // $flow_data = D('Flow')->getAllFlowData($api_order_data['d_flow_id'],$api_order_data['d_area']);
                // $openid = $datas['openid'];
                // $discount = D('Discount')->getDiscountData2($flow_data['pay_price'],$openid,1,time(),$flow_data['d_del']);
                // $topay_price = (intval($flow_data['pay_price']))-(intval($flow_data['dis_price']));
                // if($discount){
                //   $flow_data['dis_price'] = $discount['d_dis_price'];
                // }else{
                //   $flow_data['dis_price'] = 0;
                // }
                // $topay_price = (intval($flow_data['pay_price']))-(intval($flow_data['dis_price']));
                // if($order_data['d_price'] == $topay_price ){
                //     $this->getApiService1(
                //         $api_order_data['d_user_phone'],
                //         $api_order_data['d_openid'],
                //         $api_order_data['d_out_trade_no'],
                //         $api_order_data['d_type'],
                //         $api_order_data['d_size'],
                //         $api_order_data['d_price'],
                //         $api_order_data['d_area'],
                //         $api_order_data['d_del']
                //     );
                // }
            }
        }
        echo 'SUCCESS';
    }

    public function actionPrint($id)
    {
        $orderinfo = OrderDkhKdsy::findOne($id);
        if (!empty($orderinfo)) {
            if(!empty($orderinfo['printinfo'])){
                return $this->render('print', ['PrintTemplate' => $orderinfo['printinfo']]);
            }
            //构造电子面单提交信息
            $type = [1 => '文件', 2 => '数码产品', 3 => '生活用品', 4 => '服饰', 5 => '食品', 6 => '其他'];
            $eorder = [];
            $express_type = Express::findByid($orderinfo->express_type);
            if ($express_type['express_code'] != 'SF') {
                if ($orderinfo->cid) {
                    $res = AppExpress::findByWhere([
                        'type' => $orderinfo->express_type,
                        'cid' => $orderinfo->cid,
                        'status' => 1,
                    ]);
                    if (empty($res['customer_number'])) {
                        echo '客户号不存在';
                        exit();
                    } else {
                        $eorder['CustomerName'] = $res['customer_number'];
                        if ($express_type['express_code'] == 'YTO') {
                            $eorder['MonthCode'] = $res['customer_pwd'];
                        } else {
                            $eorder['CustomerPwd'] = $res['customer_pwd'];
                        }
                        if($express_type['express_code'] == 'STO'  || $express_type['express_code'] == 'HHTT'  ){
                            $eorder['SendSite'] = $res['network_name'];
                        }
                        $eorder['CustomerName'] = $res['customer_number'];
                        $eorder['MonthCode'] = $res['customer_pwd'];
                    }
                } else {
                    echo '无快递类型';
                    exit();
                }
            }

            $eorder["ShipperCode"] = $express_type['express_code'];// 顺丰
            $eorder["OrderCode"] = $orderinfo->code;// 订单号K 开头
            $eorder["PayType"] = 1;
            $eorder["ExpType"] = 1;
            $eorder["Weight"] = $orderinfo->weight_low; // 公斤数
            if($orderinfo->express_type == 5  or $orderinfo->express_type == 4){
                $eorder["TemplateSize"] = 180;
            }
            $sender = [];
            $sender["Name"] = $orderinfo->begin_name;// 起始地
            $sender["Mobile"] = $orderinfo->begin_mobile; // 电话
            $sender["ProvinceName"] = $orderinfo->begin_province; // 省
            $sender["CityName"] = $orderinfo->begin_city; // 市
            $sender["ExpAreaName"] = $orderinfo->begin_dist; // 区
            $sender["Address"] = $orderinfo->begin_detail; // 详细地址
            $receiver = [];
            $receiver["Name"] = $orderinfo->end_name; // 终点
            $receiver["Mobile"] = $orderinfo->end_mobile; // 电话
            $receiver["ProvinceName"] = $orderinfo->end_province; // 省
            $citys = ['上海市'=>'上海市','重庆市'=>'重庆市','天津市'=>'天津市','北京市'=>'北京市'];
            if(in_array($orderinfo->end_province, $citys)){
                $receiver["CityName"] = $citys[$orderinfo->end_province]; // 市
            }else{
                $receiver["CityName"] = $orderinfo->end_city; // 市
            }
            $receiver["CityName"] = $orderinfo->end_city; // 市
            $receiver["ExpAreaName"] = $orderinfo->end_dist; // 区
            $receiver["Address"] = $orderinfo->end_detail; // 详细地址
            $commodityOne = [];
            $commodityOne["GoodsName"] = $type[$orderinfo->type];// 物品
            $commodityOne["GoodsWeight"] = $orderinfo->weight_low;
            if(!$commodityOne["GoodsName"]){
                $commodityOne["GoodsName"] = 1;
            }
            $commodity = [];
            $commodity[] = $commodityOne;
            $eorder["Sender"] = $sender;
            $eorder["Receiver"] = $receiver;
            $eorder["Commodity"] = $commodity;
            $eorder['IsReturnPrintTemplate'] = 1;
            $jsonParam = json_encode($eorder, JSON_UNESCAPED_UNICODE);
            $jsonResult = $this->submitEOrder($jsonParam);
            $res = json_decode($jsonResult);
            if (!isset($res->PrintTemplate)) {
                echo $res->Reason;
                exit();
            }
            // $res->PrintTemplate = str_replace("1kg",$orderinfo['weight_low'].'kg',$res->PrintTemplate);
            // KdnLog::log(json_encode($res));
            DkhMoneyLog::add($orderinfo);
            $admin = Admin::findOne($orderinfo->admin_id);
            // $number = $admin->number;
            // $admin->number = $number-1;
            $adminRes = $admin->save();
            OrderDkhKdsy::complete($orderinfo->id,$res->Order->LogisticCode);
            $orderinfo->printinfo = $res->PrintTemplate;
            $orderinfo->save();
            return $this->render('print', ['PrintTemplate' => $res->PrintTemplate]);
        } else {
            exit('订单不存在');
        }
    }
}